import { LOGIN_TYPE, LOGOUT_TYPE } from '../actions/user'

let userInfo = localStorage.getItem('userInfo')
try { userInfo = JSON.parse(userInfo) || {} } catch { userInfo = {} }

const initState = { userInfo }

const reducer = function (state = initState, { type, payload }) {
  let newState;
  switch (type) {
    case LOGIN_TYPE:
      newState = { userInfo: payload }
      localStorage.setItem('userInfo', JSON.stringify(payload))
      return newState
    case LOGOUT_TYPE:
      newState = { userInfo: {} }
      localStorage.removeItem('userInfo')
      return newState
    default:
      return state
  }
}
export default reducer
